from email.header import Header
from email.mime.text import MIMEText
from email.utils import formataddr
import smtplib


class Mail:
    def __init__(self, server, port, username, password, nickname=None):
        self.host = server
        self.port = int(port)
        self.user = username
        self.password = password
        self.nickname = nickname

    def _get_server(self):
        if self.port == 465:
            server = smtplib.SMTP_SSL(self.host, self.port)
        else:
            server = smtplib.SMTP(self.host, self.port)
        server.login(self.user, self.password)
        return server

    def send_text_mail(self, receivers, subject, body):
        server = self._get_server()
        msg = MIMEText(body, 'plain', 'utf-8')
        msg['Subject'] = Header(subject, 'utf-8')
        msg['From'] = formataddr((self.nickname, self.user)) if self.nickname else self.user
        server.sendmail(self.user, receivers, msg.as_string())
        server.quit()


# 第三方 SMTP 服务
mail_host = 'smtp.exmail.qq.com'  #设置服务器
mail_user = 'zabbix@qipeizhanggui.com'    #用户名
mail_pass = '1qaz2wsX'   #口令

sender = 'zabbix@qipeizhanggui.com'


def send_email(content, email):
    message = MIMEText(content, 'plain', 'utf-8')
    message['From'] = Header('VPN管理员', 'utf-8')
    message['To'] = Header(email, 'utf-8')

    subject = 'VPN文件下载通知'
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)
        smtpObj.ehlo()
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, email, message.as_string())
        print('邮件发送成功')
    except smtplib.SMTPException:
        print('Error: 无法发送邮件')
